<template>
      <!-- 主要编辑区域 -->
      <div class="bg-white rounded-xl p-6 shadow-sm">
        <div class="text-gray-500 mb-6  flex items-center space-x-2">
           <span v-if="mode=='创建试卷'" class="font-bold"> {{ questionNumber }}</span>
           <span>{{ currentType }}</span>
           <div v-if="mode=='创建试卷'"  class="flex items-center space-x-1">
            <el-input  class="w-16 mx-2 "  v-model="scores[scores.findIndex(item=>item.type==currentType)].score" />
              <span>分</span> 
            </div>
        </div>
        <div class="mb-6">
          <!-- 富文本工具栏 题干 -->
           <div  class="h-300 mb-6 ">
           <RichTextEditor :html="questionForm.questionContent" @change="getHtml" />
           </div>
          <!--选择题选项列表 -->
          <div v-if="questionForm.questionType==='单选题'|| questionForm.questionType==='多选题'">
            <div class="space-y-4">
              <div v-for="(option, index) in questionForm.options" :key="index" class="flex  space-x-4" @mouseenter="option.isClose=true"  @mouseleave="option.isClose=false">
                <el-tooltip
                  effect="dark"
                  content="设为答案"
                  placement="top">
                <span :class="['text-gray-500 w-8 h-8  leading-8 text-center border ',currentType=='多选题'?'rounded-lg':'rounded-full',option.isAnswer?'bg-blue-500 text-white':'',
                 ]"
                  @click="choiceAnswer(index)">{{ String.fromCharCode(65 + index) }} </span>
              </el-tooltip>
                <div  class="border border-gray-200  rounded-lg p-2 w-full" v-show="!option.isEditing" 
                  @click="handleClickOption(index)" >
                  <span  v-show='option.content.trim()=="" || option.content=="<p><br></p>"' class="text-gray-400">请输入选项{{String.fromCharCode(65 + index)}}内容</span>
                  <span v-html="option.content" ></span>
                </div>
                  <div class="flex-1" v-show="option.isEditing" >
                    <RichTextEditor :html="option.content" @change="(html)=>{option.content = html}" />
                  </div>
                <div class="w-8">
                  <el-button v-if="option.isClose" class="font-bold text-xl" type="info" icon="Close" link @click="removeOption(index)"  />
                </div>
              </div>
            </div>

            <!-- 添加选项按钮 -->
            <el-button 
              type="primary" 
              link
              class="mt-4 !rounded-button"
              @click="addOption">
              <el-icon class="mr-2"><Plus /></el-icon>
              添加选项
            </el-button>
          </div>
          <!-- 填空题 -->
          <div v-else-if="questionForm.questionType==='填空题'">
            <div class="space-y-4">
              <div v-for="(option, index) in questionForm.gapOptions" :key="index" class="flex  space-x-6" @mouseenter="option.isClose=true"  @mouseleave="option.isClose=false">
                <span :class="['text-gray-500 w-8 h-8 leading-8 text-center  whitespace-nowrap' ]">第{{ index+1 }}空</span>
              
                <div  class="border border-gray-200  rounded-lg p-2 w-full" v-show="!option.isEditing" 
                  @click="handleClickOption(index)" >
                  <span  v-show='option.content.trim()===""' class="text-gray-400">请输入答案</span>
                  <span v-html="option.content"></span>
                </div>
                
                  <div class="flex-1" v-show="option.isEditing" >
                    <RichTextEditor :html="option.content" @change="(html)=>{option.content = html}" />
                  </div>
                <div class="w-8">
                  <el-button v-if="option.isClose" class="font-bold text-xl" type="info" icon="Close" link @click="removeGapOption(index)"  />
                </div>
              </div>
            </div>

            <!-- 添加选项按钮 -->
            <el-button 
              type="primary" 
              link
              class="mt-4 !rounded-button"
              @click="addGapOption">
              <el-icon class="mr-2"><Plus /></el-icon>
               添加更多
            </el-button>
            <div v-if="currentType=='填空题'" class="text-gray-500/80  text-[12px] my-4 space-y-2 px-2">
              <div>1. 一个空有多种答案时请用";"隔开。如：答案一;答案二</div>
              <div>2. 若试题答案是数字，可设置范围，两个数字之间用"-"。如：1-9，学生填写1到9之间的数字都算正确（包括1和9）</div>
            </div>

          </div>
          <!-- 判断题 -->
          <div v-else-if="questionForm.questionType==='判断题'">
             <div class="space-y-4">
               <div v-for="(option, index) in judgeOptions" :key="index" class="flex  space-x-4">
                  <el-tooltip
                  effect="dark"
                  content="设为答案"
                  placement="top">
                <span :class="['text-gray-500 w-8 h-8  leading-8 text-center border rounded-full',option.isAnswer?'bg-blue-500 text-white':'' ]"
                  @click="choiceAnswer(index)">{{ String.fromCharCode(65 + index) }}</span>
              </el-tooltip>
                <span>{{ option.content }}</span>
              </div>

             </div>
            
          </div>
          <!-- 简答题其他都通简答题的模版 -->
          <div v-else>
               <div  class="border border-gray-200  rounded-lg p-2 w-full"  @click="handleEssay"  v-show="!isShowEssayEditor">
              <span v-show='questionForm.essayAnswer==""' class="text-gray-400">请输入答案</span>
              <span v-html="questionForm.essayAnswer"></span>
             </div>
             <RichTextEditor v-show="isShowEssayEditor" :html="questionForm.essayAnswer" @change="html=>questionForm.essayAnswer=html"/>
          </div>
        </div>

        <!-- 答案解析 -->
        <div class="mb-6">
             <div  class="border border-gray-200  rounded-lg p-2 w-full" v-show="!questionForm.analysis.isEditing" @click="handleClickAnalysis">
              <span v-show='questionForm.analysis.content==""' class="text-gray-400">请输入答案解析</span>
              <span v-html="questionForm.analysis.content"></span>
             </div>
         <RichTextEditor :html="questionForm.analysis.content" @change="(html)=>{questionForm.analysis.content = html}"  v-show="questionForm.analysis.isEditing"/>
        </div>

        <!-- 难度设置 -->
        <div class="mb-6 flex items-center gap-4">
          <div class="text-gray-600 mb-2 w-20 ">难度</div>
          <el-select v-model="questionForm.difficulty" placeholder="请选择难度" class="w-40">
            <el-option
              v-for="item in difficulties"
              :key="item.value"
              :label="`(${item.value}) ${item.label}`"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 知识点 -->
        <div class="mb-6 flex items-center ">
          <div class="text-gray-600 mb-2  w-20">知识点</div>
          <div class="ml-4 flex flex-wrap items-center">
            <el-tag
                v-for="tag in questionForm.knowledgePoints"
                :key="tag"
                class="mr-2"
                size="large"
                closable
                @close="removeKnowledgePoint(tag)"
            >
                {{ tag }}
            </el-tag>
            <el-button 
                class="!rounded-button" 
                @click="showAddKnowledgePoint = true">
                <el-icon><Plus /></el-icon>
                添加知识点
            </el-button>
          </div>
        </div>
        <!-- 标签 -->
        <div class="mb-6 flex items-center ">
          <div class="text-gray-600 mb-2 w-20 ">标签</div>
          <div class="ml-4 flex flex-wrap items-center">
            <el-tag
                v-for="tag in questionForm.tags"
                :key="tag"
                size="large"
                class="mr-2"
                closable
                @close="removeTag(tag)"
            >
                {{ tag }}
            </el-tag>
            
            <el-button 
                class="!rounded-button" 
                @click="showTagsDialog = true">
                <el-icon><Plus /></el-icon>
                关联标签
            </el-button>
          </div>
        </div>

         <!-- 提交按钮 -->
      <div class="mt-6 py-4 flex items-center justify-center bg-white" v-if="mode =='创建题目'">
         <el-button type="success" @click="saveQuestion">保存</el-button>
        <el-button type="primary" @click="EditNextQuestion">继续出题</el-button>
      </div>
      <div class="mt-6 py-4 flex items-center justify-center bg-white" v-else-if="mode =='创建试卷'">
        <el-button  round class="w-20">重置</el-button>
        <el-button type="primary" round class="w-20" @click="saveQuestion">完成</el-button>
      </div>
      <div class="mt-6 py-4 flex items-center justify-center bg-white" v-else-if="mode =='编辑'">
        <el-button type="success" @click="saveQuestion">保存</el-button>
        <el-button type="primary" @click="EditNextQuestion">保存为新题</el-button>
      </div>
      </div>
      <KnowledgeAndTagDialog  v-model:showAddKnowledgePoint="showAddKnowledgePoint" v-model:showTagsDialog="showTagsDialog" 
      @sendKnowledgeData="addKnowledgeToQuestion" @sendTagData="addTagsToQuestion" />
</template>

<script  setup>
import { ref,watch,nextTick, reactive,onMounted,toRefs} from 'vue';
import 'katex/dist/katex.min.css'
import katex from 'katex'
import { Plus } from '@element-plus/icons-vue';
import { useRouter,useRoute } from 'vue-router';
import RichTextEditor from '@/components/RichTextEditor.vue';
import KnowledgeAndTagDialog from '@/views/exam/KnowledgeAndTagDialog.vue';
const props = defineProps({
  questionId: { type: String, default: '' },// 题目id
  mode: { type: String, default: '创建题目' },// 创建题目、创建试卷、 编辑题目
  questionData: { type: Object, default: () => ({}) },// 题目数据
  currentType: { type: String,default: '单选题' },// 题目类型
  questionNumber:{type:Number,default:1},//题目序号
  isSave:{type:Boolean,default:false}
});
const emit = defineEmits(['update:questionData','update:isSave']);
const  {currentType,mode,questionNumber} =toRefs(props);
const router = useRouter();
const  route = useRoute();//判断是否传递参数id
onMounted(()=>{
  if(route.query.id){//如果有传递参数id，则加载题目详情
    const id = route.query.id;
    console.log("id:",id)
    // getQuestionDetailById(id);
  }
})

//定义整个表单数据 
const questionForm = reactive({
  id: null,
  questionType:props.currentType,//当前题型
  questionContent: '',//题目内容
  options: [//选项
    { content: '',isEditing: false,isClose:false,isAnswer:false },
    { content: '',isEditing: false,isClose:false,isAnswer:false},
    { content: '',isEditing: false,isClose:false,isAnswer:false},
    { content: '',isEditing: false,isClose:false,isAnswer:false }
  ],
  gapOptions:[
    { content: '',isEditing: false,isClose:false,isAnswer:false },
  ],//填空题每个空答案
  answer: [], //选择/多选题答案
  essayAnswer:'',//简答题答案
  analysis:{content:'',isEditing:false},//答案解析
  difficulty: '0.8',//难度
  knowledgePoints: [],//知识点
  tags: [],//标签 
})
//判断题选项
const judgeOptions = ref([
  { content: '正确', value: true ,isAnswer:true},
  { content: '错误', value: false,isAnswer:false }
]);
// 题目默认分值 
const  scores = ref([
    { type: '单选题', score: 5.0 },
    { type: '多选题', score: 5.0 },
    { type: '填空题', score: 5.0 },
    { type: '判断题', score: 5.0 },
    { type: '简答题', score: 5.0 },
]);


const showAddKnowledgePoint = ref(false);
// 关联标签
const  showTagsDialog = ref(false);

const difficulties = [
  { value: '0.1', label: '难' },
  { value: '0.2', label: '难' },
  { value: '0.3', label: '中' },
  { value: '0.4', label: '中' },
  { value: '0.5', label: '中' },
  { value: '0.6', label: '中' },
  { value: '0.7', label: '中' },
  { value: '0.8', label: '易' },
  { value: '0.9', label: '易' },
  { value: '1.0', label: '易' },
];

watch(()=>props.questionData,(newVal)=>{
    // console.log(newVal,'=========传递参数回显题目=========');
    if(newVal.questionId==undefined && newVal.id==undefined) return;
    questionForm.id = newVal.id?newVal.id:newVal.questionId;
    questionForm.questionType = newVal.questionType;
    questionForm.questionContent = newVal.questionContent; // 题目内容

    questionForm.options = newVal.options; // 选项
    questionForm.gapOptions = newVal.gapOptions;//填空题每个空答案
    questionForm.answer = newVal.answer; // 选择题的正确答案

    questionForm.analysis.content = newVal.analysis;
    questionForm.difficulty = newVal.difficulty; // 难度
    questionForm.knowledgePoints = newVal.knowledgePoint?newVal.knowledgePoints:[]; // 知识点
    questionForm.tags = newVal.tags?newVal.tags:[]; // 标签

    // questionForm.options.forEach((item,index) => { 
    //   if(questionForm.answer.includes(item.option) ){
    //     item.isAnswer = true;
    //   }
    // });
    // console.log('************************************');
    
},{immediate:true ,deep:true})
watch(()=>props.currentType,(newVal)=>{ 
    console.log('当前题型：',newVal);
    questionForm.questionType = newVal;
    questionForm.options.forEach(item=>{item.isAnswer= false;})
   
    
},{immediate:true})
// 当选项内容变化时，重新渲染公式
watch(()=>questionForm.options,(newVal)=>{
  // console.log('选项变化：',newVal);
   nextTick(() => {
    // 匹配富文本编辑器生成的公式span元素
    document.querySelectorAll('span[data-w-e-type="formula"]').forEach(span => {
      const latex = span.getAttribute('data-value')
      if (latex) {
        // 清空span内容并渲染公式
        span.innerHTML = ''
        katex.render(latex, span, {
          displayMode: false, // 内联公式
          throwOnError: false,
          trust: (context) => ['\\htmlId', '\\href'].includes(context.command)
        })
      }
    })
  })

},{deep:true})



// 富文本编辑器内容变化事件
const getHtml = (html) => {
  questionForm.questionContent = html;
};

/**
* 添加选项
* 如果选项数组的长度小于26，则向选项数组中添加一个新的空选项对象。
*/
const addOption = () => {
  if(questionForm.options.length < 26) {
    questionForm.options.push({ content: '' });
  }
};
/**
* 删除选项
* 如果选项数组的长度大于1，则从选项数组中删除最后一个选项对象。
*/
const removeOption = (index) => {
  if(questionForm.options.length > 1) {
    questionForm.options.splice(index, 1);
  }
}
// 添加填空题的答案 
const  addGapOption = () => {
  questionForm.gapOptions.push({ content: '' });
}
//删除填空题的answer
const  removeGapOption = (index) => {
  if(questionForm.gapOptions.length > 1) {
    questionForm.gapOptions.splice(index, 1);
  }
}

// 点击了某个选项的显示富文本
const  handleClickOption = (index) => {
//   if(currentType.value === 0|| currentType.value === 1) {//如果单选或者多选
  if(currentType.value === '单选题'|| type.value === '多选题') {//如果单选或者多选
      questionForm.analysis.isEditing = false;//关闭解析的富文本编辑器

      questionForm.options.forEach((item,i)=>{
        if(index === i) {
          item.isEditing = true;
        }else {
          item.isEditing = false;
        }
      })
  }else if(currentType.value === '填空题') {//如果是填空题
    questionForm.analysis.isEditing = false;
    questionForm.gapOptions.forEach((item,i)=>{
      if(index === i) {
        item.isEditing = true;
      }else {
        item.isEditing = false;
      }
    })

    }

};
// 某个或者某些选项设为答案
const choiceAnswer=(index) => {
  console.log(index,'index选择选项',currentType.value,'currentType');
  // 题目为单选的情况 
  if(currentType.value === '单选题') {//单选题
    console.log('单选',1111);
    questionForm.options.forEach((item,i)=>{
      item.isAnswer = false;
    })
    questionForm.options[index].isAnswer = true;
    let answer = String.fromCharCode(65 + index);
    questionForm.answer = [answer];
  }else if(currentType.value==='多选题' ) { //题目为多选的情况
    questionForm.options[index].isAnswer = !questionForm.options[index].isAnswer;
  }else if(currentType.value==='判断题' ) { //题目为判断题的情况
    judgeOptions.value.forEach((item,i)=>{
      item.isAnswer = false;
    })
    judgeOptions.value[index].isAnswer = !judgeOptions.value[index].isAnswer;
  }

  
};
// 简答题答案编辑
const isShowEssayEditor = ref(false);
//点击输入简答题的答案
const  handleEssay=() => { 
  isShowEssayEditor.value = true;
  questionForm.analysis.isEditing = false;
  questionForm.options.forEach(item=>{
    item.isEditing = false;
  })
};

//点击编辑
 const  handleClickAnalysis = () => {
  questionForm.analysis.isEditing = true;
  questionForm.options.forEach(item=>{
    item.isEditing = false;
  })
  isShowEssayEditor.value = false;
};
// 删除知识点
const removeKnowledgePoint = (knowledgePoint) => {
  questionForm.knowledgePoints= questionForm.knowledgePoints.filter(t => t !== knowledgePoint);
};
// 删除标签
const removeTag = (tag) => {
  questionForm.tags = questionForm.tags.filter(t => t !== tag);
};


// 从知识带你的弹框中获取到选择的知识点
const addKnowledgeToQuestion=(knowledge) => { 
  console.log(knowledge,'knowledge');
  knowledge.forEach(item=>{
    if(!questionForm.knowledgePoints?.includes(item.name)){
      questionForm.knowledgePoints?.push(item.name)
    }
  })

};

//从标签的弹框中获取到选择的标签
const addTagsToQuestion = (tag) => {
  console.log(tag,'tag',questionForm.tags)
  tag.forEach(item=>{
    if(!questionForm.tags?.includes(item.name)){
      questionForm.tags?.push(item.name)
    }
  })
}


//保存题目
 const saveQuestion = () => {
  console.log('点击了保存题目的按钮》》',questionForm)
  //todo 保存到题目到数据库
  emit("update:questionData",questionForm)
  emit('update:isSave',true)
 }

 //继续出题
 const   EditNextQuestion = () => {
  console.log('点击了继续出题的按钮》》')
 }

 onMounted(() => { 
  console.log('创建题目的组件创建----');
 })


</script>

<style scoped>
.el-input :deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}

.el-textarea :deep(.el-textarea__inner) {
  box-shadow: none !important;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}

.el-select :deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}
</style>